<template>
  <div>
    <a-spin :spinning="spinning">
    <top-nav-bar :applyPageRoute="nowRouteTitle" @back="back"></top-nav-bar>
    <a-card :bordered="false" class="nowPage">
      <a-row style="padding-bottom:20px;">
        <!-- <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" ref="ruleForm"> -->
        <a-col :span="8">
          <span>
            <span class="titledis">考试名称:</span>
            {{form.name}}
          </span>
        </a-col>
        <a-col :span="8">
          <span>
            <span class="titledis">考试科目:</span>
            {{form.subject_name}}
          </span>
        </a-col>
        <a-col :span="8">
          <span>
            <span class="titledis">满分:</span>
            {{form.full_marks}}
          </span>
        </a-col>
      </a-row>
      <a-row style="padding-bottom:12px;">
        <a-col :span="8">
          <span>
            <span class="titledis">考试时间:</span>
            {{form.time}}
          </span>
        </a-col>
        <a-col :span="8">
          <span>
            <span class="titledis">成绩来源:</span>
            {{form.source_type==1?'机构内':'机构外'}}
          </span>
        </a-col>
      </a-row>
      <!-- </a-form-model> -->
      <a-row style="border-top:1px solid #e8e8e8; padding-top:12px;">
        <a-col :span="8">
          <span>
            <span class="titledis">是否展示给家长:</span>
            {{form.is_show==1?'展示':'不展示'}}
          </span>
        </a-col>
        <a-col :span="8">
          <span>
            <span class="titledis">排名、最高分、平均分是否展示给家长:</span>
            {{form.is_statistics_show==1?'展示':'不展示'}}
          </span>
        </a-col>
      </a-row>
    </a-card>
    <a-card :bordered="false" style="margin-top:25px;margin-bottom:80px;">
      <div style="display:flex; align-items: center;margin-bottom:15px;">
        <a-button @click="open1" style="margin-right:8px">添加学生</a-button>
        <a-button @click="open2" style="margin-right:12px">添加班级</a-button>
        <div style="width:100%;">
          <a-alert
            message="保存草稿或发布时会自动计算最高分、平均分、学员排名"
            type="warning"
            showIcon
            style="height: 32px;font-size:12px; border:none;"
          />
        </div>
      </div>

      <a-table
        :columns="columns"
        :dataSource="form.score_arr"
        :pagination="false"
        :rowKey="record => record.student_id"
       
      >
        <span slot="status" slot-scope="text,record">
          <a-radio-group @change="handleSizeChange(record)" v-model="record.status">
            
            <a-radio-button :value="1">参加考试</a-radio-button>
            <a-radio-button :value="2">缺考</a-radio-button>
          </a-radio-group>
          <span v-if="record.status==1" style="margin-left:10px;">
            <a-input-number
              id="inputNumber"
              :min="0"
              :max="form.full_marks"
              v-model="record.score"
            />分
          </span>
        </span>
        <span slot="comment" slot-scope="text,record">
          <a-textarea
            placeholder="请输入(150字以内)"
            :autoSize="{ minRows: 2, maxRows: 6 }"
            v-model="record.comment"
            :maxLength="150"
          />
        </span>
        <span slot="action" slot-scope="text,record">
          <a href="javascript:;" style="margin-left:10px;" @click="table_del(record.id)">删除</a>
        </span>
      </a-table>
    </a-card>
    <a-modal
      title="选择学生"
      v-model="visible1"
      @ok="handleOk1"
      :destroyOnClose="true"
      okText="选好了"
      width="800px"
    >
      <a-form>
        <a-row>
          <a-col :span="7">
            <a-form-item>
              <a-input
                v-model="studentName"
                placeholder="请输入学员名称(回车搜索)"
                @pressEnter="$refs.table1.refresh(true)"
              >
                <a-tooltip slot="suffix" title="请输入学员名称">
                  <a-icon
                    type="search"
                    style="color: rgba(0,0,0,.45)"
                    @click="$refs.table1.refresh(true)"
                  />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <s-table
        ref="table1"
        :rowKey="(record) => record.id"
        :columns="stuColumns"
        :data="loadStuData"
        :rowSelection="{ selectedRowKeys: stuselectedRowKeys, onChange: stuonSelectChange,getCheckboxProps:getCheckboxProps1 }"
        :scroll="{y:300}"
      ></s-table>
    </a-modal>

    <a-modal
      title="选择班级"
      v-model="visible2"
      @ok="handleOk2"
      :destroyOnClose="true"
      okText="选好了"
      width="800px"
    >
      <a-form>
        <a-row>
          <a-col :span="8">
            <a-form-item>
              <a-input
                v-model="className"
                placeholder="请输入班级名称(回车搜索)"
                style="width:80%"
                @pressEnter="$refs.table2.refresh(true)"
              >
              <a-tooltip slot="suffix" title="请输入班级名称">
                  <a-icon
                    type="search"
                    style="color: rgba(0,0,0,.45)"
                    @click="$refs.table2.refresh(true)"
                  />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item>
              <a-select
                v-model="queryParam2.course_id"
                placeholder="所属课程"
                style="width:80%"
                allowClear
              >
                <a-select-option v-for="item in this.Iscourses" :key="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item>
              <a-select
                v-model="queryParam2.teacher_id"
                placeholder="授课老师"
                style="width:80%"
                allowClear
              >
                <a-select-option v-for="item in this.Isteacher" :key="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <s-table
        ref="table2"
        :rowKey="(record) => record.id"
        :columns="classColumns"
        :data="loadClassData"
        :rowSelection="{ selectedRowKeys: classselectedRowKeys, onChange: classonSelectChange,getCheckboxProps:getCheckboxProps2 }"
        :scroll="{y:300}"
      >
        <span
          slot="student_num"
          slot-scope="text, record"
        >{{record.student_num}}/{{record.upper_limit}}</span>
      </s-table>
    </a-modal>
    <a-card
      :bordered="false"
      style="position: fixed;bottom: 0;left: 0;right: 0;padding: 0px 20px 0px 0px;margin: 0; background: #fff; display: flex;
    align-items: center;
    justify-content: flex-end;
    height:48px"
    >
      <a-button type="primary" @click="onSubmit(1)">发布</a-button>
      <a-button style="margin-left: 10px;" @click="onSubmit(2)">保存为草稿</a-button>
    </a-card>
     </a-spin>
  </div>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
// import StepByStepModal from '../../list/modules/StepByStepModal'
// import CreateForm from '../../list/modules/CreateForm'
import { subjectsList, examsCreate, getExams, examsUpdate,examsDel } from '@/api/homeSchool'
import { classList } from '@/api/class'
import { studentList } from '@/api/student'
import { teacherList } from '@/api/teacher'
import { coursesList } from '@/api/courseCharge'
import topNavBar from '@/components/topNavBar/topNavBar'

export default {
  name: 'Single',
  components: {
    topNavBar,
    STable
  },
  data() {
    return {
      spinning:false,
      aa:1,
      stuselectedRowKeys: [], //选择的  清空他用 this.selectedRowKeys = [];
      classselectedRowKeys: [], //选择的  清空他用 this.selectedRowKeys = [];
      selectedRowKeys1: [], //真正要用的，学员
      selectedRowKeys2: [], //真正要用的，班级
      stuColumns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          align: 'center'
        },
        {
          title: '年级',
          dataIndex: 'grade_name',
          align: 'center'
        }
      ],
      classColumns: [
        {
          title: '班级名称',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '班级老师',
          dataIndex: 'teacher',
          align: 'center',
          customRender(teacher) {
            if (teacher.length > 0) {
              let teachers = teacher.map(function(item) {
                return item.name
              })
              return teachers.join('/')
            }
          }
        },
        {
          title: '人数/容量',
          dataIndex: 'student_num',
          align: 'center',
          scopedSlots: { customRender: 'student_num' }
        }
      ],
      visible1: false,
      visible2: false,
      studentName: undefined,
      className:undefined,
      queryParam1: {}, // 查询参数
      queryParam2: {}, // 查询参数

      visible: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        time: undefined,
        subject_id: undefined,
        school_id: undefined,
        is_show: '1',
        source_type: '1',
        type: '1', //1正式，2草稿
        is_statistics_show: '1',
        full_marks: 0,
        score_arr: [
          // {
          //   student_id: 6,
          //   name: '学员姓名1',
          //   status: '2',
          //   comment: 'New York No. 1 Lake Park',
          //   score: '2'
          // },
          // {
          //   student_id: 4,
          //   name: 'John Brown',
          //   status: '1',
          //   comment: 'New York No. 1 Lake Park',
          //   score: '23'
          // },
          // {
          //   student_id: 11,
          //   name: 'John Brown',
          //   status: '1',
          //   comment: 'New York No. 1 Lake Park',
          //   score: '2' //默认为0
          // }
        ]
      },
      form_time: '', //日期
      nowRouteTitle: '',
      Isclass: [],
      Isstudent: [], //学员的数据，用选好的班级id和学生id做筛选
      Iscourses: [],
      Isteacher: [],
      Issubjects: [],
      rules: {
        subject_id: [{ required: true, message: '请选择', trigger: 'change' }],
        full_marks: [{ required: true, message: '请输入数字' }],
        time: [{ required: true, message: '请选择' }],
        source_type: [{ required: true, message: '请选择' }],
        name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },

      columns: [
        {
          title: '学员姓名',
          dataIndex: 'student_name',
          key: 'student_name',
          align: 'center'
        },
        {
          title: '分数',
          dataIndex: 'status',
          key: 'status',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '评语(选填)',
          dataIndex: 'comment',
          key: 'comment',
          align: 'center',
          scopedSlots: { customRender: 'comment' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadStuData: parameter => {
        return studentList(
          Object.assign(
            parameter,
            { school_id: this.$store.state.user.school, keywords: this.studentName },
            this.queryParam1
          )
        ).then(res => {
          return res
        })
      },
      loadClassData: parameter => {
        return classList(Object.assign(parameter, this.queryParam2, { school_id: this.$store.state.user.school,keywords:this.className })).then(
          res => {
            return res
          }
        )
      },
      getCheckboxProps1: record => ({
        props: {
          disabled: this.selectedRowKeys1.some(item => item == record.id) // Column configuration not to be checked
        }
      }),
      getCheckboxProps2: record => ({
        // props: {
        //   disabled: this.selectedRowKeys2.some(item => item == record.id) // Column configuration not to be checked
        // }
      })
    }
  },
  watch: {
    queryParam2: {
      handler(val) {
        this.$refs.table2.refresh(true)
      },
      deep: true
    }
  },
  created() {
    this.school_id = this.$store.state.user.school //获取school_id
    this.$store.state.Isfather = false
    this.nowRouteTitle = this.$route.meta.title
    subjectsList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      // 获取科目信息
      this.Issubjects = res.data
    })
    teacherList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      // 获取老师信息
      this.Isteacher = res.data
    })
    coursesList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      // 获取课程信息
      this.Iscourses = res.data
    })
    classList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      this.Isclass = res.data
    })
    studentList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      this.Isstudent = res.data
    })
    let id = this.$route.query.id
    this.getInfo()
  },
  destroyed() {
    this.$store.state.Isfather = true
  },

  methods: {
    getInfo(){
      this.spinning=true
    getExams(this.$route.query.id).then(res => {
      this.form = res
    }).catch(err=>{
      this.$message.error(err.data.message||'成绩单详情获取失败请重试')
    }).finally(()=>{
        this.spinning=false
    })
    },
    handleSizeChange(data) {
      if (data.status == 2) {
        this.form.score_arr.forEach(function(item) {
          if (item.student_id == data.student_id) {
            item.score = 0
          }
        })
      }
    },
    table_del(id) {
      let that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除此学员吗?',
        okText: '删除',
        cancelText: '取消',
        onOk() {
          examsDel(id).then(res=>{
            that.getInfo()
            that.$message.success('删除成功')
          }).catch(err=>{
            that.$message.error(err.data.message||"删除失败")
          })
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    back() {
      this.$router.go(-1)
    },
    onChange(date, dateString) {
      this.form_time = dateString //要
    },
    onSubmit(e) {
      this.form.type = e
        if(this.form.score_arr.length==0){
        this.$message.warning("请先添加学生")
         return
      }

      //验证通过
      let data =JSON.parse(JSON.stringify(this.form))
      delete data.highest_score
      delete data.average_score
      data.school_id = this.$store.state.user.school
      data.score_arr = data.score_arr.map(function(item) {
        return { student_id: item.student_id, status: item.status, comment: item.comment, score: item.score }
      })
      let id = this.$route.query.id
      examsUpdate(data, id)
        .then(res => {
          this.$message.success("成绩编辑成功")
          this.$router.go(-1)
        })
        .catch(err => {
          this.$message.error(err.data.message || '发布/保存草稿失败')
        })
    },
    showModal() {
      this.visible = true
    },
    handleOk(e) {
      this.visible = false
    },

    open1() {
      this.visible1 = true
    },
    open2() {
      this.visible2 = true
    },

    handleOk1() {
      //模态框确认1
      let selectedRowKeys = this.selectedRowKeys
      // this.form.project_ids = this.selectedRowKeys
      this.selectedRowKeys1 = this.stuselectedRowKeys
      let _this = this
      let score_arr = []
      let form_score_arr = this.form.score_arr
      this.Isstudent.map(function(item) {
        if (_this.selectedRowKeys1.some(listItem => listItem == item.id)) {
          score_arr.push({ student_id: item.id, student_name: item.name, status: '1', comment: '', score: 0 })
        }
      })
      form_score_arr = form_score_arr.concat(score_arr)
      let object = {}
      if (form_score_arr.length > 0) {
        this.form.score_arr = form_score_arr.reduce((item, next) => {
          object[next.student_id] ? '' : (object[next.student_id] = true && item.push(next))
          return item
        }, [])
      } else {
        this.form.score_arr = form_score_arr
      }

      this.visible1 = false
    },
    handleOk2() {
      //模态框确认2
      this.selectedRowKeys2 = this.classselectedRowKeys
      let _this = this
      let schoolId = this.$store.state.user.school
      this.selectedRowKeys2.map(function(item) {
        studentList({ pageSize: 999999, school_id: schoolId, class_id: item }).then(res => {
          // studentarr = studentarr.concat(res.data)
          if (res.data.length > 0) {
            res.data.map(function(data) {
              if (!_this.form.score_arr.some(arrItem => arrItem.student_id == data.id)) {
                _this.form.score_arr = _this.form.score_arr.concat({
                  student_id: data.id,
                  student_name: data.name,
                  status: '1',
                  comment: '',
                  score: 0
                })
              }
            })
          }
        })
      })
      this.visible2 = false
    },

    stuonSelectChange(selectedRowKeys) {
      this.stuselectedRowKeys = selectedRowKeys
    },
    classonSelectChange(selectedRowKeys) {
      this.classselectedRowKeys = selectedRowKeys
    }
  }
}
</script>
<style lang="less" scoped>
.nowPage {
  padding: 0 8px;
}
.a_row_bottom {
  border-bottom: 1px solid #c0c0c0;
  width: 100%;
  margin: 10px 0;
}
.titledis {
  padding-right: 5px;
}
</style>